package com.hang.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hang.model.Attendance;
import com.hang.model.Task;
import com.hang.service.AttendanceService;
import com.hang.service.TaskService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * 定时任务类，每隔五分钟完成一次对数据库的打卡信息的统计
 */
@Configuration
@EnableScheduling
@EnableAsync
@Slf4j
public class StatisticsTaskConfig {
    @Autowired
    private TaskService taskService;

    @Autowired
    private AttendanceService attendanceService;

    @Autowired
    private RedisConfig redisConfig;

    @Scheduled(cron = "0 0/5 7-23 ? * 1,2,3,4,5,6")
    @Async
    public void statisticsTask(){
//        log.info(LocalDateTime.now() + "---统计开始---");

        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(1);

        //获取到达截至时间之前的任务列表
        List<Task> tasks = taskService.getRecentlyTasks();

        //对任务表的考勤情况进行统计
        for(Task task : tasks){
            Long taskId = task.getTaskId();
            String id = String.valueOf(taskId);
            if(StringUtils.isNotBlank(id) && redisTemplate.opsForHash().size(id)>0){
                Map<String,Integer> entries = redisTemplate.<String,Integer>opsForHash().entries(id);
                int realCount = 0;      //实到人数
                int leaveCount = 0;     //请假人数

                for (Map.Entry<String, Integer> entry : entries.entrySet()) {
                    final String key = entry.getKey();
                    final Integer value = entry.getValue();

                    if(!key.equals("realCount")&&value == 1){
                        realCount++;
                    }

                    if(!key.equals("leaveCount") && value ==2){
                        leaveCount++;
                    }
                }

                redisTemplate.opsForHash().put(id,"realCount",realCount);
                redisTemplate.opsForHash().put(id,"leaveCount",leaveCount);
                task.setRealCount(realCount);

                taskService.updateById(task);
            }
        }

//        log.info(LocalDateTime.now() + "---统计结束---");
    }

    /**
     *     需要完成每日任务统计,每天晚上11点将今天的任务进行统计
     *
     *     TODO 考虑将打卡之中的数据库写入删掉
     */

    @Scheduled(cron = "0 30 23 ? * 1,2,3,4,5,6")
    @Async
    public void statisticsTaskEveryDay(){
//        log.info(LocalDateTime.now() + "---同步开始---");

        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(1);

        List<Task> tasks = taskService.getTodayTasks();

        for (Task task : tasks) {
            //昨日任务列表统计
            final Long taskId = task.getTaskId();

            String id = String.valueOf(taskId);

            if(StringUtils.isNotBlank(id) && redisTemplate.opsForHash().size(id) > 0){
                final Map<String, Integer> entries = redisTemplate.<String, Integer>opsForHash().entries(id);

                for(Map.Entry<String,Integer> entry: entries.entrySet()){
                    final String key = entry.getKey();
                    final Integer value = entry.getValue();

                    QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("student_id",key);
                    queryWrapper.eq("task_id",taskId);

                    Attendance attendance = attendanceService.getOne(queryWrapper);
                    attendance.setStatus(value);

                    //更新数据库状态
                    attendanceService.updateById(attendance);
                }
            }
        }
//        log.info(LocalDateTime.now() + "---同步完成---");
    }
}
